//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================
#include <ddk.h>
#include "pen.h"

#define MOUSE_UP                  0

typedef struct _MOUSEDATA {
    int MouseAction;
    int x;
    int y;
}MOUSEDATA;

physaddr_t PenPhysAddr;
void * PenVirAddr;

ECode CPen::Read(
                /* [in] */ Int64 u64Offset,
                /* [in] */ Int32 bytesToRead,
                /* [out] */ MemoryBuf * pBuffer,
                /* [out] */ IEvent * * ppCompletionEvent)
{
    if (pBuffer == NULL ||
        pBuffer->GetCapacity() < (int)sizeof(TOUCH_DATA)) {
        return E_INVALID_ARGUMENT;
    }

    int ret = 0;
    TOUCH_DATA tData;
    MOUSEDATA *pmData;
    pmData = (MOUSEDATA *)PenVirAddr;
    tData.dir = (short)pmData->MouseAction;
    tData.x = (short)pmData->x;
    tData.y = (short)pmData->y;
    pBuffer->Copy((Byte *)&tData, sizeof(TOUCH_DATA));
    ret = pBuffer->GetUsed();
    if (ret != sizeof(TOUCH_DATA)) {
        return E_FAIL;
    }
    return NOERROR;
}

ECode  CPen::Write(
                /* [in] */ Int64 u64Offset,
                /* [in] */ const MemoryBuf & buffer,
                /* [out] */ Int32 * pBytesWritten,
                /* [out] */ IEvent * * ppCompletionEvent)
{
    return E_NOT_IMPLEMENTED;
}

ECode CPen::Control(
                /* [in] */ Handle32 nControlCode,
                /* [in] */ const MemoryBuf & inBuffer,
                /* [out] */ MemoryBuf * pOutBuffer,
                /* [out] */ IEvent * * ppCompletionEvent)
{
    return NOERROR;
}

void CPen::Dispose()
{
}

#if 0
static void CDECL IOPenISR(irq_t irq, void * pvDevice,
                InterruptContext * pContext)
{
}
#endif

static Boolean IOPenInit()
{
    //DzRegisterIsr(16, IPL1, (isr_t)IOPenISR, NULL);

    PenPhysAddr = DzAllocPages(0, 0);
    if (PenPhysAddr == INVALID_PAGE_ADDRESS) {
        kprintf("IOPenInit, DzAllocPages Fail \n");
        return FALSE;
    }
    PenVirAddr = __VA(PenPhysAddr);
    Outl(0x8e000004, PenPhysAddr);
    return TRUE;
}

EXTERN IDeviceDriver * CDECL CreateTouch(uint_t uDeviceNo, void *pvParameter)
{
    IDeviceDriver *pDriver;

    pDriver = new CPen();
    if (NULL == pDriver) return NULL;
    pDriver->AddRef();
    if (!IOPenInit()) {
        pDriver->Release();
        return NULL;
    }

    return pDriver;
}
